/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.kruders.validator;

/**
 *
 * @author Araika
 */
import java.util.List;
 
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.kruders.domain.Login;
import com.kruders.model.bean.User;
import com.kruders.util.HibernateUtil;
 
import org.hibernate.Session;
 
public class LoginValidator implements Validator{
    @Override
    public boolean supports(Class<?> clazz) {
        return Login.class.isAssignableFrom(clazz);
    }
 
    @Override
    public void validate(Object target, Errors errors) {
        Login loginuser = (Login) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<User> userList = session.createQuery("from User where username ='" + loginuser.getEmail() + "' and password ='" + loginuser.getPassword() + "'").list();
        if(userList.size() == 0) {
            errors.reject("wrongcredential","Wrong Username or Password!!!");   
        }
         
    }
}
